package com.viknix.threadpool.manager.http.request;

import com.viknix.threadpool.manager.http.interceptor.HttpClientRequestInterceptor;
import com.viknix.threadpool.manager.http.model.RequestHttpEntity;
import com.viknix.threadpool.manager.http.response.HttpClientResponse;

import java.io.IOException;
import java.net.URI;
import java.util.Iterator;

/**
 * @Author: Dongqi
 * @Date: 2021/11/22 10:57
 * @Version 1.0
 * @Description: Wrap http client request and perform corresponding interception.
 */
public class InterceptingHttpClientRequest implements HttpClientRequest {
    
    private final HttpClientRequest httpClientRequest;
    
    private final Iterator<HttpClientRequestInterceptor> interceptors;
    
    public InterceptingHttpClientRequest(HttpClientRequest httpClientRequest,
                                         Iterator<HttpClientRequestInterceptor> interceptors) {
        this.httpClientRequest = httpClientRequest;
        this.interceptors = interceptors;
    }
    
    @Override
    public HttpClientResponse execute(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity)
            throws Exception {
        while (interceptors.hasNext()) {
            HttpClientRequestInterceptor nextInterceptor = interceptors.next();
            if (nextInterceptor.isIntercept(uri, httpMethod, requestHttpEntity)) {
                return nextInterceptor.intercept();
            }
        }
        return httpClientRequest.execute(uri, httpMethod, requestHttpEntity);
    }
    
    @Override
    public void close() throws IOException {
        httpClientRequest.close();
    }
}
